package cn.k7g.alloy.ioc;

import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.exception.AlloyContentDecodeException;
import cn.k7g.alloy.exception.AlloyMessageException;
import cn.k7g.alloy.expose.AlloyContentHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 支持query参数
 * @author victor-wu
 * @date 2021/9/27 下午1:10
 */
@Component
public class AlloyContentResolve implements HandlerMethodArgumentResolver {

    @Autowired
    private AlloyContentHandler handler;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(AlloyContent.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String parameterValue = webRequest.getParameter(parameter.getParameterName());
        try {
            return handler.decodeObject(parameterValue, parameter.getParameterType());
        } catch (AlloyContentDecodeException e) {
            throw new AlloyMessageException(e);
        }
    }
}
